package com.valuegroup.smarttodo.data.service;

import android.os.Build;

import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.Goals;
import com.valuegroup.smarttodo.data.model.Curriculum;
import com.valuegroup.smarttodo.data.model.Event;
import com.valuegroup.smarttodo.data.model.Habit;
import com.valuegroup.smarttodo.data.model.HabitOrder;
import com.valuegroup.smarttodo.data.model.HabitOrderRelate;
import com.valuegroup.smarttodo.data.model.Tag;
import com.valuegroup.smarttodo.data.model.Task;
import com.valuegroup.smarttodo.data.model.TaskStep;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;

import java.util.Date;
import java.util.List;
import java.util.Random;

import androidx.annotation.RequiresApi;

public class DataInitService extends BaseService {

    private Random random = new Random();


    private static final String[] dataHabit = new String[]{
            "早上6点钟起床#一日之计在于晨#15#false#",
            "学习与研究#每天都花时间学习新的东西#25#true#",
            "享用美味可口的早餐#一天中最重要的一餐#5#false#",
            "冥想10分钟#提高你的注意力和同情心#35#false#",
            "阅读感兴趣的内容#享受阅读的快乐#10#false#",
            "晚间11点前睡觉#保证规律的睡眠时间#15#false#",
            "充电小睡#醒来后精力充沛！#15#false#",
            "写日记#写作本身就是奖赏#10#true#",
            "创建时间表#分时段安排你的任务，并提前做好计划#20#true#",
            "喝茶#茶是完美的饮料选择#15#false#",
            "多吃水果蔬菜#方便，有利健康#15#false#",
            "有意识的专注工作#完全专注于当前任务#20#true#",
            "瑜伽#缓解压力，更加灵活#15#false#",
            "获取灵感#花一点时间来得到灵感#10#false#",
            "记录我的时间#不要让时间悄悄的溜走#15#false#",
            "跑步5KM#体育锻炼让身体更健康#5#false#"
    };

    private static final String[] dataHabitOrder = new String[]{
            "早晨习惯",
            "午间习惯",
            "晚间习惯"
    };

    // 初始化测试数据
    public void initTaskListTestData() {
        if (getTaskDao().loadAll().size() > 0) {
            System.out.println("Task 数据存在");
            return;
        }

        for (int i = 0; i < 20; i++) {
            Task t = ServiceFactory.getInstance().getTaskService().getDefaultTaskData();

            // 特殊数据设置
            switch (i) {
                case 0:
                case 10:
                    // 完成状态
                    t.setFinishDt(new Date());
                    t.setIsFinish(true);
                    break;
                case 1:
                case 11:
                    // 星标
                    t.setIsStar(true);
                    break;
                case 2:
                    // 提醒
                    t.setRemindType(AppStatus.RemindType.NOW);
                    t.setRepeatType(AppStatus.RepeatType.EVERYDAY);
                case 12:
                    t.setRemindType(AppStatus.RemindType.AHEAD10);
                    break;
                case 3:
                case 13:
                    // 过期任务日期需要标红
                    t.setCreatedDt(DateUtils.moveDay(new Date(), -10));
                    t.setIsPastDue(true);
                    break;
            }

            // 随机给定截止日期
            t.setDeadline(DateUtils.moveDay(DateUtils.moveDay(-2), random.nextInt(5)));

            getTaskDao().insert(t);
            t.setTitle(t.getTitle() + t.getId());
            t.setCreatedDt(DateUtils.moveDay(t.getCreatedDt(), random.nextInt(10)));
            getTaskDao().save(t);

            if (i > 15) {
                // 无步骤
            } else {
                for (int j = 0; j < (random.nextInt(8)); j++) {
                    TaskStep s = ServiceFactory.getInstance().getTaskService().getDefaultTaskStepData(t.getId());
                    // 随机标识完成状态
                    s.setIsFinish((random.nextInt(20) % 2 == 1));
                    s.setTitle(s.getTitle() + j);
                    getTaskStepDao().insert(s);
                }
            }
        }

        System.out.println("初始化Task数据");
    }


    public void initHabitListTestData() {
        if (getHabitDao().loadAll().size() > 0) {
            System.out.println("Habit 数据存在");
            return;
        }

        for (int i = 0; i < dataHabit.length; i++) {
            Habit t = ServiceFactory.getInstance().getHabitService().getDefaultHabit();
            String[] dataArr = (dataHabit[i]).split("#");
            t.setTitle(dataArr[0]);
            t.setDesc(dataArr[1]);
            t.setPreMinute(Integer.parseInt(dataArr[2]));

            getHabitDao().save(t);
        }
    }


    private Habit getRandomHabit(List<Habit> hlist) {
        Habit h = null;
        boolean isJoin = true;
        while (isJoin) {
            h = hlist.get(random.nextInt(hlist.size()));
            isJoin = ServiceFactory.getInstance().getHabitService().isHabitJoin(h.getId());
        }
        return h;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void initHabitOrderData() {
        if (getHabitOrderDao().loadAll().size() > 0) {
            System.out.println("HabitOrder 数据存在");
            return;
        }

        List<Habit> hlist = ServiceFactory.getInstance().getHabitService().findHabit(null);

        for (int i = 0; i < 3; i++) {
            HabitOrder order = ServiceFactory.getInstance().getHabitService().getDefaultHabitOrder();
            order.setTitle(dataHabitOrder[i]);
            order = ServiceFactory.getInstance().getHabitService().saveHabitOrder(order);

            for (int j = 0; j < 3; j++) {
                Habit h = getRandomHabit(hlist);

                HabitOrderRelate or = new HabitOrderRelate();
                or.setHid(h.getId());
                or.setOrderId(order.getId());

                or.setBeginDt(new Date());
                or.setRepeatType(AppStatus.RepeatType.EVERYDAY);
                or.setEndDt(DateUtils.moveDay(90));

                or.setSort(j);
                or.setStatus(AppStatus.Status.NORMAL);
                or.setCreatedDt(new Date());
                or.setUpdatedDt(new Date());
                ServiceFactory.getInstance().getHabitService().saveHabitOrderRelate(or);

            }

        }
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    public void initGoalData() {
        if (getGoalsDao().loadAll().size() > 0) {
            System.out.println("initGoalData 数据存在");
            return;
        }

        // 生成年度目标
        for (int yearSize = 1; yearSize <= 20; yearSize++) {
            genYearGoal(2018 + random.nextInt(5) + 1);
        }

        for (int year = 2018; year <= 2024; year++) {
            genYearGoal(year);

            // 生成季度目标
            for (int quarterSize = 1; quarterSize <= 20; quarterSize++) {
                Goals quarterGoal = ServiceFactory.getInstance().getGoalsService().getDefaultGoals();
                quarterGoal.setGoalsRange(AppStatus.GoalsRange.QUARTER);
                quarterGoal.setRangeQuarter(random.nextInt(4) + 1);
                quarterGoal.setRangeYear(year);
                quarterGoal.setRangeMonthly(0);
                quarterGoal.setDeadline(DateUtils.getLastDayOfMonth2Date(year, quarterGoal.getRangeQuarter() * 3));
                quarterGoal.setFinishDt(null);
                quarterGoal.setTitle(year + "年" + quarterGoal.getRangeQuarter() + "季度目标" + quarterSize);
                quarterGoal.setIsFinish(false);
                quarterGoal.setIsStar(random.nextBoolean());
                ServiceFactory.getInstance().getGoalsService().getGoalsDao().save(quarterGoal);
                quarterGoal.setTitle(quarterGoal.getTitle() + "主键是" + quarterGoal.getId());
                ServiceFactory.getInstance().getGoalsService().getGoalsDao().save(quarterGoal);

                genRandomEvent(true, quarterGoal.getId(), quarterGoal.getTitle());
            }

            // 生成月度目标
            for (int monthSize = 1; monthSize <= 20; monthSize++) {
                Goals monthGoal = ServiceFactory.getInstance().getGoalsService().getDefaultGoals();
                monthGoal.setGoalsRange(AppStatus.GoalsRange.MONTHLY);
                monthGoal.setRangeMonthly(random.nextInt(12) + 1);
                monthGoal.setRangeYear(year);
                monthGoal.setRangeQuarter(0);
                monthGoal.setDeadline(DateUtils.getLastDayOfMonth2Date(year, monthGoal.getRangeMonthly()));
                monthGoal.setFinishDt(null);
                monthGoal.setTitle(year + "年" + monthGoal.getRangeMonthly() + "月度目标" + monthSize);
                monthGoal.setIsFinish(false);
                monthGoal.setIsStar(random.nextBoolean());
                ServiceFactory.getInstance().getGoalsService().getGoalsDao().save(monthGoal);
                monthGoal.setTitle(monthGoal.getTitle() + "主键是" + monthGoal.getId());
                ServiceFactory.getInstance().getGoalsService().getGoalsDao().save(monthGoal);

                genRandomEvent(true, monthGoal.getId(), monthGoal.getTitle());
            }
        }

        // 生成目标事件

    }

    private void genRandomEvent(boolean isGoal, Long id, String parentTitle) {
        Event e = null;
        for (int i = 0; i < random.nextInt(6); i++) {
            if (isGoal) {
                e = ServiceFactory.getInstance().getGoalsService().getDefaultEvent(id);
            } else {
                e = ServiceFactory.getInstance().getCurriculumService().getDefaultEvent(id);
            }
            e.setTitle(parentTitle + "的" + e.getTitle() + i);
            ServiceFactory.getInstance().getEventService().getEventDao().save(e);
        }
    }

    private void genYearGoal(int year) {
        Goals yearGoal = ServiceFactory.getInstance().getGoalsService().getDefaultGoals();
        yearGoal.setGoalsRange(AppStatus.GoalsRange.YEAR);
        yearGoal.setRangeYear(year);
        yearGoal.setRangeMonthly(0);
        yearGoal.setRangeQuarter(0);
        yearGoal.setTitle("年度目标" + year);
        yearGoal.setDeadline(DateUtils.getYearLast(year));
        yearGoal.setFinishDt(null);
        yearGoal.setIsFinish(false);
        yearGoal.setIsStar(random.nextBoolean());
        ServiceFactory.getInstance().getGoalsService().getGoalsDao().save(yearGoal);
        yearGoal.setTitle(yearGoal.getTitle() + "主键" + yearGoal.getId());
        ServiceFactory.getInstance().getGoalsService().getGoalsDao().save(yearGoal);

        genRandomEvent(true, yearGoal.getId(), yearGoal.getTitle());
    }

    public void initCurriculumData() {
        if (getCurriculumDao().loadAll().size() > 0) {
            System.out.println("Curriculum 数据存在");
            return;
        }

        for (int i = 0; i < 5; i++) {
            Curriculum t = ServiceFactory.getInstance().getCurriculumService().getDefaultCurriculum();
            t.setTitle(t.getTitle() + i);
            getCurriculumDao().save(t);

            // 随机生成事件
            for (int j = 0; j < random.nextInt(6); j++) {
                Event e = ServiceFactory.getInstance().getCurriculumService().getDefaultEvent(t.getId());
                e.setTitle(t.getTitle() + "的" + e.getTitle() + j);
                e.setFinish(false);
                if (e.getFinish()) {
                    e.setFinishDt(DateUtils.moveDay(new Date(), 5));
                }
                getEventDao().save(e);
            }
        }
    }


    public void initTags() {
        if (getTagDao().loadAll().size() > 0) {
            System.out.println("Tag 数据存在");
            return;
        }
        String[] arr = new String[]{"家庭", "生活", "事业", "旅行", "创业", "工作", "小孩", "钢琴", "超长内容的标签", "山水田园"};
        for (String s : arr) {
            Tag t = ServiceFactory.getInstance().getTagService().getDefaultTag(s);
            getTagDao().save(t);
        }
    }

}
